package com.walterlife.javacore;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIOServer
 *
 * @author zhuyuwei
 * @date 2017/4/7
 */
public class NIOServer {
    /**
     * 通道管理器
     */
    private Selector selector;

    private void initServer(int port) throws Exception {
        // 获得ServerSocket通道
        ServerSocketChannel channel = ServerSocketChannel.open();
        // 设置非阻塞
        channel.configureBlocking(false);
        // 将socket绑定到port端口
        channel.socket().bind(new InetSocketAddress(port));
        // 获得selector管理器
        this.selector = Selector.open();
        // 注册感兴趣事件，当事件到达时，selector.selector()会返回
        // 否则会一直阻塞
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }

    private void listen() throws Exception {
        System.out.println("start listening");

        while (true) {
            selector.select();
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                ite.remove();
                // 服务端socket接受客户端socket连接
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    // 获取与客户端连接的socket channel
                    SocketChannel channel = server.accept();
                    // 配置非阻塞
                    channel.configureBlocking(false);
                    // 向客户端发送数据
                    channel.write(ByteBuffer.wrap(new String("Hello Client").getBytes()));
                    // client socket 注册读事件
                    channel.register(this.selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {  // socket读就绪
                    read(key);
                }
            }
        }
    }

    private void read(SelectionKey key) throws Exception {
        // 获取客户端socket channel 方便读取数据
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 将数据从channel读取到buffer中
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("server receive from client " + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer);
    }

    public static void main(String[] args) throws Exception {
        NIOServer server = new NIOServer();
        server.initServer(20001);
        server.listen();
    }
}
